package com.dgut.forum.services.impl;

import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.dao.ArticleMapper;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.Article;
import com.dgut.forum.model.User;
import com.dgut.forum.services.IArticleService;
import com.dgut.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private BoardServiceImpl boardService;
    @Autowired
    private UserServiceImpl userService;


    @Override
    public int create(Article article) {
        if(article==null
                ||article.getUserId()<0
                ||article.getBoardId()<0
                ||StringUtil.stringNoLength(article.getTitle())
                ||StringUtil.stringNoLength(article.getContent())){
            log.info("新增文章,参数校验失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setVisitCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        int ret=articleMapper.insertSelective(article);
        if(ret!=1){
            log.warn("新增文章失败");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        Long userId=article.getUserId();
        if(userId==null||userId<0){
            log.warn("新增用户文章数量失败,id="+userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ADD_COUNT));
        }
        userService.addOneToUserArticleCount(userId);

        Long boardId=article.getBoardId();
        if(boardId==null||boardId<0){
            log.warn("新增版块文章数量失败,id="+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ADD_COUNT));
        }
        boardService.addOneToBoardArticleCount(boardId);

        log.info("新增文章成功 user id="+userId+", board id="+boardId+" article id="+article.getId());
        return ret;
    }

    /*
    * 查询首页所有的文章
    * */
    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    /*
    * 根据版块Id查询所属版块的所有文章
    *
    * */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        return articleMapper.selectAllByBoardId(boardId);
    }

    /*
     * 根据用户Id查询用户的所有文章,用户主页展示
     *
     * */
    @Override
    public List<Article> selectAllByUserId(Long userId) {
        if(userId==null||userId<=0){
            log.warn("查找用户主页帖子时,用户Id不合法,用户ID="+userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectAllByUserId(userId);
    }

    @Override
    public Article selectDetailById(Long Id) {
        if(Id==null||Id<0){
            log.warn("查询文章详情失败，文章id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查到文章详情
        Article article=articleMapper.selectDetailById(Id);
        //判断文章是否存在
        if(article==null){
            log.warn("查询文章详情失败，文章id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle=new Article();
        updateArticle.setId(Id);
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int ret=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(ret!=1){
            log.info("更新文章访问数量失败，文章id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode. ERROR_SERVICES));
        }
        //更新放回文章的访问次数，与数据库同步
        article.setVisitCount(article.getVisitCount()+1);
        //更新文章访问次数
        return article;
    }


    /*
    * 修改文章
    *
    * */
    @Override
    public void modify(Long Id, String title, String content) {
        if(Id<=0
            ||StringUtil.isEmpty(title)
            ||StringUtil.isEmpty(content)){
            log.error("修改帖子时传入的参数异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=new Article();
        article.setId(Id);
        article.setTitle(title);
        article.setContent(content);

        int row = articleMapper.updateByPrimaryKeySelective(article);
        if(row!=1){
            log.error("修改帖子失败");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info("修改帖子成功");
    }

    /*
    * 选择帖子
    *
    * */
    @Override
    public Article selectById(Long Id) {
        if(Id<=0){
            log.error("修改文章时传入的参数异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        return articleMapper.selectById(Id);
    }


    /*
    * 点赞帖子
    *
    * */
    @Override
    public void thumbsUpById(Long Id) {
        if(Id<=0){
            log.error("点赞帖子时传入的参数异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article=articleMapper.selectById(Id);
        if(article==null||article.getDeleteState()==1){
            log.warn("帖子为空,帖子id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            log.warn("帖子已经封贴,id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED_STATE));
        }
        Article updateArticle=new Article();
        updateArticle.setId(Id);
        updateArticle.setLikeCount(article.getLikeCount()+1);

        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("修改帖子失败");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info("点赞帖子成功");
    }

    /*
    * 删除帖子
    *
    * */
    @Override
    public void delete(Long Id) {
        if(Id==null||Id<=0){
            log.warn("删除帖子,帖子Id不合法,id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectById(Id);
        if(article==null){
            log.warn("要删除的帖子不存在,帖子Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1||article.getDeleteState()==1){
            log.warn("要删除的帖子已经被封贴或者删除了,帖子Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle=new Article();
        updateArticle.setId(Id);
        updateArticle.setDeleteState((byte) 1);
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("删除帖子时,服务器出错,Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        userService.subOneToUserArticleCount(article.getUserId());
        boardService.subOneToBoardArticleCount(article.getBoardId());

        log.info("删除帖子成功,帖子Id="+ Id);
    }

    /*
    * 帖子回复数量加一
    * */
    @Override
    public void addOneToArticleReplyCount(Long Id){
        if(Id==null||Id<=0){
            log.warn("更新帖子回复数量,帖子Id不合法,id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectById(Id);
        if(article==null){
            log.warn("更新帖子回复数量帖子不存在,帖子Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1||article.getDeleteState()==1){
            log.warn("要更新帖子回复数量时帖子已经被封贴或者删除了,帖子Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        Article updateArticle=new Article();
        updateArticle.setId(Id);
        updateArticle.setReplyCount(article.getReplyCount()+1);
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("更新帖子回复数量时,服务器出错,Id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info("增加帖子回复数量成功,帖子Id="+ Id);
    }
}
